package com.btl.component.crypto.aes.advice;

import com.btl.component.crypto.aes.AesSecurityCrypt;
import com.btl.component.crypto.aes.annotation.AesSec;
import com.btl.component.crypto.aes.exception.DecryptException;
import jakarta.annotation.Resource;
import org.springframework.core.MethodParameter;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.HttpInputMessage;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.lang.NonNull;
import org.springframework.util.StreamUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.RequestBodyAdvice;

import java.io.IOException;
import java.lang.reflect.Type;
import java.nio.charset.StandardCharsets;
import java.util.Objects;

@ControllerAdvice
public class AesDecryptRequestBodyAdvice implements RequestBodyAdvice {

    @Resource
    private RedisTemplate<String, Object> redisTemplate;

    @Override
    public boolean supports(MethodParameter parameter, @NonNull Type targetType, @NonNull Class<? extends HttpMessageConverter<?>> converterType) {
        return parameter.hasMethodAnnotation(AesSec.class);
    }

    @Override
    @NonNull
    public HttpInputMessage beforeBodyRead(HttpInputMessage inputMessage, @NonNull MethodParameter parameter, @NonNull Type targetType, @NonNull Class<? extends HttpMessageConverter<?>> converterType) throws IOException {
        String encryptedData = StreamUtils.copyToString(inputMessage.getBody(), StandardCharsets.UTF_8);
        if (inputMessage.getHeaders()
                .containsKey("Sec-Key-Id")) {
            String keyId = inputMessage.getHeaders()
                    .getFirst("Sec-Key-Id");
            if (StringUtils.hasText(keyId)) {
                Object key = redisTemplate.opsForValue()
                        .get(keyId);
                if (Objects.nonNull(key)) {
                    return AesSecurityCrypt.decrypt(key.toString(), encryptedData, inputMessage.getHeaders());
                }
            }
        }
        throw new DecryptException("解密异常");
    }

    @Override
    @NonNull
    public Object afterBodyRead(@NonNull Object body, @NonNull HttpInputMessage inputMessage, @NonNull MethodParameter parameter, @NonNull Type targetType, @NonNull Class<? extends HttpMessageConverter<?>> converterType) {
        return body;
    }

    @Override
    public Object handleEmptyBody(Object body, @NonNull HttpInputMessage inputMessage, @NonNull MethodParameter parameter, @NonNull Type targetType, @NonNull Class<? extends HttpMessageConverter<?>> converterType) {
        return body;
    }
}